package com.gk.panda.commons.rsa;



import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

@Component
public class RsaService {

//    private PublicKey publicKey;
//
//    private PrivateKey privateKey;
//
//    private String secure = "dxm";

    private final String secret = "pandapark";


//    public RsaService() throws Exception {
//        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
//        byte[] bytes = secure.getBytes();
//        SecureRandom random = new SecureRandom(bytes);
//        generator.initialize(2048,random);
//        KeyPair keyPair = generator.generateKeyPair();
//        publicKey = keyPair.getPublic();
//        privateKey = keyPair.getPrivate();
//    }

//    public String encrypt(String rawStr) throws Exception{
//        Cipher cipher = Cipher.getInstance("RSA");
//        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
//        byte[] bytes = cipher.doFinal(rawStr.getBytes());
//        return Base64.getEncoder().encodeToString(bytes);
//    }
//
//    public String decrypt(String encodedStr) throws Exception {
//        byte[] decode = Base64.getDecoder().decode(encodedStr);
//        Cipher cipher = Cipher.getInstance("RSA");
//        cipher.init(Cipher.DECRYPT_MODE,privateKey);
//        byte[] bytes = cipher.doFinal(decode);
//        return new String(bytes);
//    }

    public String generateToken(Map<String,Object> map){
        long time = System.currentTimeMillis();
        return Jwts.builder()
//                .setIssuer("dxm")
                .setIssuedAt(new Date(time))
                .setClaims(map)
                .setExpiration(new Date(time+30*24*60*60*1000L))
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    public Map<String,Object> parseToken(String token){
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
        return claimsJws.getBody();
    }
}
